/*
 * Copyright (C) 2008 GeoScheduler team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.alerts;

import java.util.Date;

import org.geoscheduler.android.activities.EditEvent;
import org.geoscheduler.android.exceptions.GSActualEventFindFailedException;
import org.geoscheduler.android.tools.DBHelper;
import org.geoscheduler.android.tools.DateTimeHelper;
import org.geoscheduler.model.Event;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;

/**
 * Tool for registering and unregistering alert checker timer
 * 
 * @author paja
 */
public class AlertHelper {

	protected final static long MINIMUM_TIME_BETWEEN_UPDATE = 30000; // 30 seconds
	protected final static long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 100; // 100 meters
	
	protected static LocationListener alertLL;
	
	public static void registerIntent(Context context) {
		alertLL = new AlertHelper.AlertLocListener(context);

		// Find location service
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		LocationProvider provider = lm.getProvider(EditEvent.FIXED_LOCATION_PROVIDER);
		
		// Register intent to location manager
		lm.requestLocationUpdates(provider.getName(),
				MINIMUM_TIME_BETWEEN_UPDATE,
				MINIMUM_DISTANCECHANGE_FOR_UPDATE, 
				alertLL);

        // Tell the user about what happened
//        Toast.makeText(context, R.string.al_eventcheck_registered, Toast.LENGTH_LONG).show();
	}

	public static void unregisterIntent(Context context) {
		// Find location service
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		// Unregister intent to location manager
		locationManager.removeUpdates(alertLL);

        // Tell the user about what happened
//        Toast.makeText(context, R.string.al_eventcheck_unregistered, Toast.LENGTH_LONG).show();
	}
	
	public static Event findActualEvent(Context ctx, int lat, int lon) throws GSActualEventFindFailedException {
		String now = DateTimeHelper.formatISO8601(new Date());
		
		String query = "(((alert_type = " +Event.AlertType.LOCATION.ordinal()+ ")" +
								"OR (alert_type = " +Event.AlertType.TAG.ordinal()+ "))" +
							" OR (((time_from < '" +now+ "') OR (time_from IS NULL)) AND ((time_to > '" +now+ "') OR (time_to IS NULL))))" +
				" AND (((lat_lo < "+lat+") AND (lat_hi > "+lat+")) OR (lat IS NULL))" +
				" AND (((lon_lo < "+lon+") AND (lon_hi > "+lon+")) OR (lon IS NULL))" +
				" AND (alert_type != " +Event.AlertType.NONE.ordinal()+ ")";
		
		SQLiteDatabase db = DBHelper.openDB(ctx);
		Event out = (Event) DBHelper.fetchOne(db, new Event(), query);
		db.close();
		
		return out;
	}
	
	public static class AlertLocListener implements LocationListener {
		Context ctx;
		
		public AlertLocListener(Context ctx) {
			super();
			this.ctx = ctx;
		}

		/**
		 * @see android.location.LocationListener#onLocationChanged(android.location.Location)
		 */
		@Override
		public void onLocationChanged(Location location) {
			ctx.startService(new Intent(ctx, AlertService.class));
		}
		
		// FIXME do we need to react to these?

		/**
		 * @see android.location.LocationListener#onProviderDisabled(java.lang.String)
		 */
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}

		/**
		 * @see android.location.LocationListener#onProviderEnabled(java.lang.String)
		 */
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		/**
		 * @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle)
		 */
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
		
	}
}
